package cn.school.demo.ui.article

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentViewPager2Binding
import cn.school.demo.databinding.FragmentViewPagerBinding
import cn.school.demo.pojo.Article
import com.ajguan.library.EasyRefreshLayout
import com.ajguan.library.LoadModel
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.google.gson.reflect.TypeToken
import com.mylhyl.circledialog.CircleDialog
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.bannerview.BaseBannerAdapter
import com.zhpan.bannerview.BaseViewHolder
import org.jsoup.Jsoup


class ViewPager2Fragment(val position: Int) : Fragment() {
    private lateinit var binding: FragmentViewPager2Binding
    private lateinit var viewModel: ViewPagerViewModel

    companion object {
        fun newInstance(position: Int) = ViewPager2Fragment(position)

        fun getUrlFromArticle(article: Article): MutableList<String> {
            val url = mutableListOf<String>()
            val elements = Jsoup.parse(article.articleContent).getElementsByTag("img")
            elements.forEach {
                url.add(it.attr("src"))
            }
            return url
        }

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel =
            ViewModelProvider(this).get(ViewPagerViewModel::class.java)
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_view_pager2, container, false)
        init()
        return binding.root
    }

    @SuppressLint("ResourceAsColor", "NotifyDataSetChanged", "ClickableViewAccessibility")
    fun init() {
        viewModel.getArticleByHobbyName(MyApplication.tabList[position])
            .observe(viewLifecycleOwner) {
                binding.articleProgressBar.visibility = View.GONE
                viewModel.updateArticleList(it)
                binding.mainArticleFragmentRecyclerview.apply {
                    adapter?.notifyDataSetChanged() ?: let {
                        layoutManager = LinearLayoutManager(requireContext())
                        adapter = HomeAdapter(viewModel.articleList)
                    }
                }
            }
        /* *
        * 下拉刷新
        * */
        binding.mainArticleFragmentEasyRefreshLayout.addEasyEvent(object :
            EasyRefreshLayout.EasyEvent {
            override fun onRefreshing() {
                viewModel.getArticleByHobbyName(MyApplication.tabList[position])
                    .observe(viewLifecycleOwner) {
                        binding.articleProgressBar.visibility = View.GONE
                        viewModel.updateArticleList(it)
                        binding.mainArticleFragmentRecyclerview.apply {
                            adapter?.notifyDataSetChanged() ?: let {
                                layoutManager = LinearLayoutManager(requireContext())
                                adapter = HomeAdapter(viewModel.articleList)
                            }
                        }
                        binding.mainArticleFragmentEasyRefreshLayout.refreshComplete()
                    }
            }

            override fun onLoadMore() {
                viewModel.getNextPageArticleByHobbyName(MyApplication.tabList[position])
                    .observe(viewLifecycleOwner) {
                        if (it.size != 0) {
                            viewModel.addArticleList(it)
                            binding.mainArticleFragmentRecyclerview.adapter?.notifyDataSetChanged()
                        }
                        if (it.size < viewModel.pageSize) {
                            binding.mainArticleFragmentEasyRefreshLayout.loadNothing()
                        }
                        binding.mainArticleFragmentEasyRefreshLayout.loadMoreComplete()
                    }
            }

        })

    }

    private inner class HomeHolder(view: View) : RecyclerView.ViewHolder(view),
        View.OnClickListener {
        private lateinit var article: Article
        private val timeTextView =
            itemView.findViewById<TextView>(R.id.list_item_view_page_home_time)
        private val titleTextView =
            itemView.findViewById<TextView>(R.id.list_item_view_page_home_text)
        private val imageView =
            itemView.findViewById<ImageView>(R.id.list_item_view_page_home_image_0)

        init {
            itemView.setOnClickListener(this)
        }

        @SuppressLint("SetTextI18n")
        fun bindByOneImage(article: Article, imageUrl: String) {
            this.article = article
            timeTextView.text =
                "${this.article.source} ${this.article.releaseTime.subSequence(0, 10)}"
            titleTextView.text = this.article.articleName
            Glide.with(requireContext()) //
                .load(imageUrl) //
                .placeholder(R.drawable.main_my_imageview_shape) //
                .error(R.drawable.error_picture_show) //
                .centerCrop()
                .skipMemoryCache(true)
                .into(imageView)
        }

        @SuppressLint("SetTextI18n")
        fun bindOnlyContext(article: Article) {
            this.article = article
            timeTextView.text =
                "${this.article.source} ${this.article.releaseTime.subSequence(0, 10)}"
            titleTextView.text = this.article.articleName
            imageView.visibility = View.GONE
        }

        override fun onClick(v: View) {
            MyApplication.apply {
                navigateThing["ArticleEntity"] = R.id.action_ArticleEntity_to_Article.toString()
                this.article = this@HomeHolder.article
                goto(
                    R.id.action_Article_to_ArticleEntity,
                    findNavController(),
                    parentFragmentManager
                )
            }
        }
    }

    private inner class HomeThreeImageHolder(view: View) : RecyclerView.ViewHolder(view),
        View.OnClickListener {
        private lateinit var article: Article
        private val timeTextView =
            itemView.findViewById<TextView>(R.id.list_item_view_page_home_three_image_time)
        private val titleTextView =
            itemView.findViewById<TextView>(R.id.list_item_view_page_home_three_image_text)
        private val imageView_1 =
            itemView.findViewById<ImageView>(R.id.list_item_view_page_home_three_image_1)
        private val imageView_2 =
            itemView.findViewById<ImageView>(R.id.list_item_view_page_home_three_image_2)
        private val imageView_3 =
            itemView.findViewById<ImageView>(R.id.list_item_view_page_home_three_image_3)

        init {
            itemView.setOnClickListener(this)
        }

        @SuppressLint("SetTextI18n")
        fun bind(article: Article, imageUrl: List<String>) {
            this.article = article
            timeTextView.text =
                "${this.article.source} ${this.article.releaseTime.subSequence(0, 10)}"
            titleTextView.text = this.article.articleName
            Glide.with(requireContext()) //
                .load(imageUrl[0]) //
                .placeholder(R.drawable.main_my_imageview_shape) //
                .error(R.drawable.error_picture_show) //
                .centerCrop()
                .skipMemoryCache(true)
                .into(imageView_1)
            Glide.with(requireContext()) //
                .load(imageUrl[1]) //
                .placeholder(R.drawable.main_my_imageview_shape) //
                .error(R.drawable.error_picture_show) //
                .centerCrop()
                .skipMemoryCache(true)
                .into(imageView_2)
            Glide.with(requireContext()) //
                .load(imageUrl[2]) //
                .placeholder(R.drawable.main_my_imageview_shape) //
                .error(R.drawable.error_picture_show) //
                .centerCrop()
                .skipMemoryCache(true)
                .into(imageView_3)
        }

        override fun onClick(v: View) {
            MyApplication.apply {
                navigateThing["ArticleEntity"] = R.id.action_ArticleEntity_to_Article.toString()
                this.article = this@HomeThreeImageHolder.article
                goto(
                    R.id.action_Article_to_ArticleEntity,
                    findNavController(),
                    parentFragmentManager
                )
            }
        }
    }

    private inner class HomeAdapter(var ArticleList: MutableList<Article>) :
        RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        private val ONE_IMAGE = 1
        private val MORE_IMAGE = 2
        private val NO_IMAGE = 3
        private var urlList = mutableListOf<String>()

        override fun getItemViewType(position: Int): Int {
            urlList = getUrlFromArticle(ArticleList[position])
            return when (urlList.size) {
                0 -> NO_IMAGE
                1 -> ONE_IMAGE
                2 -> ONE_IMAGE
                else -> MORE_IMAGE
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return when (viewType) {
                NO_IMAGE -> HomeHolder(
                    layoutInflater.inflate(
                        R.layout.list_item_view_page_home,
                        parent,
                        false
                    )
                )
                ONE_IMAGE -> HomeHolder(
                    layoutInflater.inflate(
                        R.layout.list_item_view_page_home,
                        parent,
                        false
                    )
                )
                else -> HomeThreeImageHolder(
                    layoutInflater.inflate(
                        R.layout.list_item_view_page_home_three_image,
                        parent,
                        false
                    )
                )
            }
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val article = ArticleList[position]
            when (getItemViewType(position)) {
                MORE_IMAGE -> (holder as HomeThreeImageHolder).bind(article, urlList)
                NO_IMAGE -> (holder as HomeHolder).bindOnlyContext(article)
                ONE_IMAGE -> (holder as HomeHolder).bindByOneImage(article, urlList[0])
            }
        }

        override fun getItemCount() = ArticleList.size
    }

}